package cn.wzvtc.miniserver;

import com.sun.net.httpserver.HttpServer;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * @author Shiwei Xu
 * @date 2020/3/3
 */
public class Environment {

  private HttpServer httpServer;
  private UserController userController;
  private UserService userService;
  private UserDao userDao;

  /**
   * Environment类的构造方法
   * 创建系统内部的对象实例，并设置互相之间的依赖
   */
  public Environment() throws Exception {
    // 如何设置实例之间的依赖？
    // 方式1： 通过构造方法，注入依赖的对象
    this.userDao = new UserDao();
    this.userService = new UserService(this.userDao);
    this.userController = new UserController(this.userService);
    // 方式2： 先创建各个实例，再通过set方法注入依赖
    // this.userController.setUserService(this.userService);

    // 创建Http服务器
    this.httpServer = initHttpServer();
  }

  private HttpServer initHttpServer() throws Exception {
    //创建一个HttpServer实例，并绑定到指定的IP地址和端口号
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
    //创建一个HttpContext，将路径为/sys/user请求映射到Dispatcher处理器
    httpServer.createContext("/sys/user", new Dispatcher(this.userController));
    //设置服务器的线程池对象
    httpServer.setExecutor(Executors.newFixedThreadPool(10));

    return httpServer;
  }

  /**
   * 运行整个系统
   */
  public void run() {
    this.httpServer.start();
  }
}
